<?php
namespace app\controller;

use app\BaseController;
// use app\controller\ForwardController;
use app\middleware\HeaderAuth;
// use think\facade\Log;

//use think\facade\Db;
use think\Request;
//中间件
/* 设备添加,设备校验,mac等 */

class EquipmentController extends BaseController
{
    protected $middleware = [HeaderAuth::class]; //控制器中间件--设备类型校验
    public function verificationEquipment(Request $re)
    {
        $header_dataType = $this->request->header('dataType');
        $request = $this->request->param();
        // Log::write($request, 'request');
        $modelName = 'app\model\\' . $header_dataType;
        $model = new $modelName;
        $equipment = $model::where('mac', $request['mac'])->find();
        if (!empty($equipment->id)) {
            foreach ($request as $key => $value) {
                $equipment->$key = $value;
            }
            $equipment->save();
        } else {
            return fail(null, 'mac不存在', -1);
        }
        return success($equipment);
    }
    public function addEquipment()
    {
        $header_dataType = $this->request->header('dataType');
        $request = $this->request->param();
        $modelName = 'app\model\\' . $header_dataType;
        $equipmentModel = new $modelName;
        foreach ($request as $key => $value) {
            $equipmentModel->$key = $value;
        }
        /* 判断是否存在该设备MAC */
        $exist=$equipmentModel::where('mac',$request['mac'])->find();//最新的一条
        if($exist){
            return fail(null,'设备已存在');
        }
        /* eid生成 类型1位数+日期3位数+编号4位数 */
        //设备类型塔机:TowerCrane，升降机：Elevator，小车：TowerCar
        $array = [
            '1' => 'TowerCrane',
            '2' => 'Elevator',
            '3' => 'TowerCar',
            '4' => 'CraneCar',
        ];
        $time =substr(date('ym',time()),-3);//3位数日期
        $last_eq_eid=$equipmentModel::order('id desc')->value('eid');//最新的一条
        $code =substr($last_eq_eid,-4);//编号5位数
        $eid = (array_search($header_dataType, $array).$time.$code)+1;
        $equipmentModel->eid = $eid;
        $equipmentModel->vcode = (string) mt_rand(1000, 9999); //生成四位数验证码--绑定
        $rq = $equipmentModel->save();
        return success($equipmentModel);
    }
}
